import React from 'react';
import PropTypes from 'prop-types';
import {Card, Button, Row, Col, Table, Form, Popconfirm, message as msg, Switch} from 'antd';
import TextInput from 'Shared/components/TextInput';
import {TABLE, FIXED_COLUMN_WIDTH, DATE_FORMAT} from '../constants';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import routes from './routes';
import {receiveData, getDetail} from './api';
const {Description} = DescriptionList;
import {injectIntl, language} from './intl';
import {lcKind, lcStatus, currency, isYesNo} from '../Enum';
import {conventEnumValueToString, formatDateTime} from '../utils';
import WrappedDatePicker from '../common/WrappedDatePicker';
import InputAmount from '../common/InputAmount';
import styles from './style.css';
import {receiveOrderValidator} from './validator';
import {uuid} from './utils';

const FormItem = Form.Item;
const YesNo = isYesNo.toList(language);

export class ReceivePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        data: {},
        details: [],
    }

    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }

    componentWillUnmount() {
        this.isunmount = true;
    }

    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        lcCashInDetail: res.data.lcCashInDetail,
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    onInvoiceCodeChange = (invoiceCode, id) => {
        const details = this.state.lcCashInDetail || [];
        const index = details.findIndex(v => v.invoiceCode === invoiceCode);
        const tmp = details.map(d => {
            if(d.id === id && index === -1)
                return Object.assign({}, d, {
                    invoiceCode,
                });
            return d;
        });
        this.setState({
            lcCashInDetail: tmp,
            hasOperat: true
        });
    }

    onPriceChange = (cashInPrice, id) => {
        const details = this.state.lcCashInDetail || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    cashInPrice,
                });
            return d;
        });
        this.setState({
            lcCashInDetail: tmp,
            hasOperat: true
        });
    }

    onCashInDateChange = (cashInDate, id) => {
        const details = this.state.lcCashInDetail || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    cashInDate,
                });
            return d;
        });
        this.setState({
            lcCashInDetail: tmp,
            hasOperat: true
        });
    }

    onCancelBillNumberChange = (cancelBillNumber, id) => {
        const details = this.state.lcCashInDetail || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    cancelBillNumber,
                });
            return d;
        });
        this.setState({
            lcCashInDetail: tmp,
            hasOperat: true
        });
    }

    onDealerPartInformationChange = (value, name, id) => {
        const details = this.state.lcCashInDetail || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    [name]: value,
                });
            return d;
        });
        this.setState({
            lcCashInDetail: tmp,
            hasOperat: true
        });
    }

    onIsCancelChange = (isCancel, id) => {
        const details = this.state.lcCashInDetail || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    isCancel
                });
            return d;
        });
        this.setState({
            lcCashInDetail: tmp,
            hasOperat: true
        });
    }

    onCancelDateChange = (cancelDate, id) => {
        const details = this.state.lcCashInDetail || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    cancelDate,
                });
            return d;
        });
        this.setState({
            lcCashInDetail: tmp,
            hasOperat: true
        });
    }

    onClickAddDetailBtn = () => {
        const details = this.state.lcCashInDetail;
        this.setState({
            lcCashInDetail: [
                ...details,
                {
                    id: uuid()
                }
            ]
        });
    };

    onDeleteAll = () => {
        this.setState({
            lcCashInDetail: [],
            hasOperat: true
        });
    }

    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const details = this.state.lcCashInDetail.filter(p => p.id !== id);
        this.setState({
            lcCashInDetail: details,
            hasOperat: true
        });
    }


    onSubmit = () => {
        const {data, lcCashInDetail} = this.state;
        const isValid = receiveOrderValidator(lcCashInDetail);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            LccCreditManagementLists: lcCashInDetail.map(v => ({
                invoiceCode: v.invoiceCode,
                cashInPrice: v.cashInPrice,
                cashInDate: v.cashInDate,
                cancelBillNumber: v.cancelBillNumber,
                isCancel: v.isCancel,
                cancelDate: v.cancelDate,
            })),
            rowVersion: data.rowVersion
        };
        this.setState({
            loading: true,
        });
        receiveData(this.props.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {data, lcCashInDetail} = this.state;
        const {formatMessage} = this.props.intl;
        const Yes = formatMessage({
            id: 'receivePanel.yes',
            defaultMessage: '是'
        });
        const No = formatMessage({
            id: 'receivePanel.no',
            defaultMessage: '否'
        });
        const columns = [
            {
                title: formatMessage({
                    id: 'receivePanel.column.invoiceCode',
                    defaultMessage: '发票号'
                }),
                dataIndex: 'invoiceCode',
                render: (text, record) => {
                    const validate = !text && this.state.isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <TextInput
                                id={record.id}
                                name="invoiceCode"
                                value={record.invoiceCode}
                                onBlur={this.onInvoiceCodeChange} />
                        </FormItem>
                    );
                }
            },
            {
                title: formatMessage({
                    id: 'receivePanel.column.cashInPrice',
                    defaultMessage: '到款金额'
                }),
                dataIndex: 'cashInPrice',
                render: (text, record) => {
                    const validate = !text && this.state.isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <InputAmount
                                id={record.id}
                                value={text}
                                onBlur={this.onPriceChange} />
                        </FormItem>
                    );
                }
            },
            {
                title: formatMessage({
                    id: 'receivePanel.column.cashInDate',
                    defaultMessage: '到款日期'
                }),
                dataIndex: 'cashInDate',
                render: (text, record) => {
                    const validate = !text && this.state.isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <WrappedDatePicker
                                name={record.id}
                                value={record.cashInDate}
                                onChange={this.onCashInDateChange} />
                        </FormItem>
                    );
                }
                    
            },
            {
                title: formatMessage({
                    id: 'receivePanel.column.cancelBillNumber',
                    defaultMessage: '核销水单号'
                }),
                dataIndex: 'cancelBillNumber',
                render: (text, record) =>
                    (
                        <FormItem>
                            <TextInput
                                id={record.id}
                                name="cancelBillNumber"
                                value={record.cancelBillNumber}
                                onBlur={this.onCancelBillNumberChange} />
                        </FormItem>
                    )
            },
            {
                title: formatMessage({
                    id: 'receivePanel.column.isCancel',
                    defaultMessage: '是否已核销'
                }),
                dataIndex: 'isCancel',
                render: (text, record) =>
                    (
                        <FormItem>
                            <Switch
                                checkedChildren={formatMessage({
                                    id: 'yes',
                                    defaultMessage: '是'
                                })}
                                unCheckedChildren={formatMessage({
                                    id: 'no',
                                    defaultMessage: '否'
                                })}
                                checked={text}
                                value={record.isCancel}
                                id={record.id}
                                onChange={value => this.onDealerPartInformationChange(value, 'isCancel', record.id)}/>
                        </FormItem>
                    )
            },
            {
                title: formatMessage({
                    id: 'receivePanel.column.cancelDate',
                    defaultMessage: '核销日期'
                }),
                dataIndex: 'cancelDate',
                render: (text, record) =>
                    (
                        <FormItem>
                            <WrappedDatePicker
                                name={record.id}
                                value={record.cancelDate}
                                onChange={this.onCancelDateChange} />
                        </FormItem>
                    )
            },
            {
                title: this.state.details.length > 0
                    ? (
                        <Popconfirm placement="topRight" title={formatMessage({
                            id: 'receivePanel.validation.isDelete',
                            defaultMessage: '是否确认全部删除？'
                        })} onConfirm={this.onDeleteAll} >
                            <a>{formatMessage({
                                id: 'receiPanel.validation.clear',
                                defaultMessage: '清空'
                            })}</a>
                        </Popconfirm>
                    )
                    : null,
                dataIndex: 'id',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                    id: 'receivePanel.validation.delete',
                    defaultMessage: '删除'
                })}</a>
            }
        ];
        return (
            <div className="detail">
                <Card loading={this.props.loading}>
                    <DescriptionList size="large" title={<Row><Col span={6}>{formatMessage({
                        id: 'receivePanel.text.title',
                        defaultMessage: '信用证信息详情'
                    })}</Col>
                    </Row>}>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.dealerCode',
                            defaultMessage: '总代编号'
                        })}>{data.dealerCode}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.dealerName',
                            defaultMessage: '总代名称'
                        })}>{data.dealerName}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.branchCode',
                            defaultMessage: '营销分公司编号'
                        })}>{data.branchCode}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.branchName',
                            defaultMessage: '营销分公司名称'
                        })}>{data.branchName}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.brandCode',
                            defaultMessage: '品牌编号'
                        })}>{data.brandCode}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.brandName',
                            defaultMessage: '品牌名称'
                        })}>{data.brandName}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.code',
                            defaultMessage: '信用证号码'
                        })}>{data.code}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.issueCountry',
                            defaultMessage: '开证国家'
                        })}>{data.issueCountry}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.issueBank',
                            defaultMessage: '开证银行'
                        })}>{data.issueBank}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.sendBank',
                            defaultMessage: '寄出银行'
                        })}>{data.sendBank}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.lcPayMentDays',
                            defaultMessage: '信用证账期'
                        })}>{data.lcPayMentDays}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.issuePrice',
                            defaultMessage: '开证金额'
                        })}>{data.issuePrice}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.issueDate',
                            defaultMessage: '开证日期'
                        })}>{formatDateTime(data.issueDate, DATE_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.lastLoadDate',
                            defaultMessage: '最迟装船日期'
                        })}>{formatDateTime(data.lastLoadDate, DATE_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.validityDate',
                            defaultMessage: '有效期'
                        })}>{formatDateTime(data.validityDate, DATE_FORMAT)}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.lcKind',
                            defaultMessage: '信用证类型'
                        })}>{conventEnumValueToString(lcKind, data.lcKind)}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.lcStatus',
                            defaultMessage: '信用证状态'
                        })}>{conventEnumValueToString(lcStatus, data.lcStatus)}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.currency',
                            defaultMessage: '币种'
                        })}>{conventEnumValueToString(currency, data.currency)}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.isBatches',
                            defaultMessage: '是否分批'
                        })}>{data.isBatches ? Yes : No}</Description>
                        <Description term={formatMessage({
                            id: 'receivePanel.text.amount',
                            defaultMessage: '件数'
                        })}>{data.amount}</Description>
                    </DescriptionList>
                </Card>
                <Card
                    title={formatMessage({
                        id: 'receivePanel.operation.detail',
                        defaultMessage: '信用证到款清单'
                    })}>
                    <Button
                        type="dashed"
                        icon="plus"
                        block
                        className={styles.plusBtn}
                        onClick={this.onClickAddDetailBtn}>
                        {formatMessage({
                            id: 'receivePanel.couponInfo.operation.new',
                            defaultMessage: '新增'
                        })}
                    </Button>
                    <Table
                        className="white-space-nowrap"
                        columns={columns}
                        rowKey="id"
                        pagination={false}
                        dataSource={lcCashInDetail}
                        {...TABLE} />
                </Card>
                <Card className={styles.optionBtn}>
                    <Button
                        type="primary"
                        onClick={this.onSubmit}
                        loading={this.state.loading}>
                        {formatMessage({
                            id: 'receivePanel.operation.onSubmit',
                            defaultMessage: '保存'
                        })}
                    </Button>
                </Card>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.props.loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'receivePanel.text.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

ReceivePanel.propTypes = {
    detail: PropTypes.object.isRequired,
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);


const mapStateToProps = (state, props) => ({
    id: props.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    detail: getDetailData(state),
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    init: () => dispatch(getDetail(props.id)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ReceivePanel));
